﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using nMongo.Tests.Entities;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace nMongo.Tests.Repository
{
    public partial class MongoRepositoryTests
    {
        [TestMethod]
        public void InsertOrUpdateSingleObject()
        {
            _MongoRepositoryTestsPrepare.RevertAnyChanges();

            MongoRepository<User> users = new MongoRepository<User>(TestsConfiguration.ConnectionString, TestsConfiguration.DatabaseName);

            User user1 = new User { Age = 20, Name = "Gustavo", IsActive = true };
            User user2 = new User { Age = 20, Name = "Beatriz", IsActive = true };
            users.InsertOrUpdate(user1);
            users.InsertOrUpdate(user2);

            user2.Age = 21;
            user2.IsActive = false;
            users.InsertOrUpdate(user2);

            // Assert
            Assert.AreEqual(2, users.Select(x => x.Name != null).Count());

            User user1test = users.GetSingle(x => x.Name == "Gustavo");
            Assert.IsTrue(user1test.IsActive);
            Assert.AreEqual(0, user1test.Age);

            User user2test = users.GetSingle(x => x.Name == "Beatriz");
            Assert.IsFalse(user2test.IsActive);
            Assert.AreEqual(0, user2test.Age);
        }

        [TestMethod]
        public void InsertOrUpdateMultipleObjects()
        {
            _MongoRepositoryTestsPrepare.RevertAnyChanges();

            MongoRepository<User> users = new MongoRepository<User>(TestsConfiguration.ConnectionString, TestsConfiguration.DatabaseName);

            IEnumerable<User> users1 = MockGenerator.GenerateList<User>(20);
            User user1 = users1.Skip(3).First();
            User user2 = users1.Skip(9).First();                        

            IEnumerable<User> usersReturned = users.InsertOrUpdate(users1);
            User user2withId = usersReturned.Single(x => x.Name == user2.Name);
            user2withId.Name = "Tested Guy";
            users.InsertOrUpdate(user2withId);

            // Assert
            Assert.AreEqual(20, users1.Select(x => x.Name != null).Count());

            IEnumerable<User> test = users.Select();

            User user1test = users.GetSingle(x => x.Name == user1.Name);
            Assert.AreEqual(user1.IsActive, user1test.IsActive);
            Assert.AreEqual(0, user1test.Age);

            User user2test = users.GetSingle(x => x.Name == "Tested Guy");
            Assert.AreEqual(user2.IsActive, user2test.IsActive);
            Assert.AreEqual(0, user2test.Age);
        }
    }
}
